<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Form, Field, Button, CellGroup, Toast, Pagination, Empty, Picker, ActionSheet } from 'vant'
import { shipmentsApi } from '../api/shipments'

type Shipment = { id?: number; order_id: number; shipment_date: string; status?: string }

// 创建发货单表单
const form = ref<Shipment>({ order_id: 0, shipment_date: new Date().toISOString().slice(0,10), status: 'Pending' })
async function create() {
  if (!form.value.order_id || !form.value.shipment_date) { Toast.fail('请填写订单ID与发货日期'); return }
  try {
    await shipmentsApi.create({ order_id: form.value.order_id, shipment_date: form.value.shipment_date, status: form.value.status })
    form.value = { order_id: 0, shipment_date: new Date().toISOString().slice(0,10), status: 'Pending' }
    await loadShipments()
    Toast.success('发货单创建成功')
  } catch (e: any) {
    const msg = e?.response?.data?.error || e?.message || '创建失败'
    Toast.fail(msg)
  }
}

// 列表/搜索/分页
const shipments = ref<Shipment[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
const qOrderId = ref<number | null>(null)
const qStatus = ref<string>('')
const showPicker = ref(false)

async function loadShipments() {
  try {
    const params: any = { page: page.value, pageSize: pageSize.value }
    if (qOrderId.value) params.order_id = qOrderId.value
    if (qStatus.value) params.status = qStatus.value
    const { data } = await shipmentsApi.getList(params)
    shipments.value = data.items || []
    total.value = data.total || 0
  } catch (e: any) {
    const msg = e?.response?.data?.error || e?.message || '加载失败'
    Toast.fail(msg)
  }
}
function search() { page.value = 1; loadShipments() }
function prevPage() { if (page.value > 1) { page.value--; loadShipments() } }
function nextPage() { if (page.value < totalPages.value) { page.value++; loadShipments() } }
function changePageSize(ps: number) { pageSize.value = ps; page.value = 1; loadShipments() }

// 行内状态更新
async function updateStatus(id: number, newStatus: string) {
  try {
    await shipmentsApi.updateStatus(id, newStatus)
    Toast.success('已更新')
    await loadShipments()
  } catch (e: any) {
    const msg = e?.response?.data?.error || e?.message || '更新失败'
    Toast.fail(msg)
  }
}

onMounted(loadShipments)
</script>

<template>
  <div class="page">
    <h2>发货</h2>

    <Form @submit.prevent="create">
      <CellGroup inset>
        <Field v-model.number="form.order_id" type="number" label="订单ID" placeholder="请输入订单ID" />
        <Field v-model="form.shipment_date" type="date" label="发货日期" />
        <Field v-model="form.status" readonly clickable label="状态" placeholder="请选择" @click="() => (showPicker=true)" />
      </CellGroup>
      <div style="padding:12px;">
        <Button type="primary" round block native-type="submit">创建发货单</Button>
      </div>
    </Form>

    <div class="filters">
      <Field v-model.number="qOrderId" type="number" label="订单ID" placeholder="按订单ID搜索" />
      <Field v-model="qStatus" label="状态" placeholder="全部状态" />
      <Button size="small" @click="search">搜索</Button>
    </div>

    <div class="table">
      <div class="t-head">
        <div class="col id">ID</div>
        <div class="col oid">订单ID</div>
        <div class="col date">发货日期</div>
        <div class="col status">状态</div>
        <div class="col ops">操作</div>
      </div>
      <div v-if="shipments.length === 0" style="padding: 12px;">
        <Empty description="暂无数据" />
      </div>
      <div class="t-row" v-for="s in shipments" :key="s.id">
        <div class="col id">{{ s.id }}</div>
        <div class="col oid">{{ s.order_id }}</div>
        <div class="col date">{{ s.shipment_date }}</div>
        <div class="col status">
          <select :value="s.status" class="native-select" @change="updateStatus(s.id as number, ($event.target as HTMLSelectElement).value)">
            <option value="Pending">Pending</option>
            <option value="Shipped">Shipped</option>
            <option value="Delivered">Delivered</option>
          </select>
        </div>
        <div class="col ops">
          <router-link :to="`/delivery/${s.order_id}`">送货单</router-link>
        </div>
      </div>
    </div>

    <div class="pager">
      <Pagination :total-items="total" :items-per-page="pageSize" :show-page-size="0" v-model:current-page="page" @change="loadShipments" />
    </div>

    <ActionSheet v-model:show="showPicker" cancel-text="取消">
      <div style="padding: 16px;">
        <Button block @click="form.status='Pending'; showPicker=false">Pending</Button>
        <Button block style="margin-top:8px;" @click="form.status='Shipped'; showPicker=false">Shipped</Button>
        <Button block style="margin-top:8px;" @click="form.status='Delivered'; showPicker=false">Delivered</Button>
      </div>
    </ActionSheet>
  </div>
</template>

<style scoped>
.page { padding-bottom: 16px; }
.table { border: 1px solid #eee; border-radius: 8px; overflow: hidden; margin: 12px 0; }
.t-head, .t-row { display: grid; grid-template-columns: 120px 1fr 1fr 1fr 140px; }
.t-head { background: #fafafa; font-weight: 600; }
.col { padding: 10px 12px; border-bottom: 1px solid #eee; }
.native-select { width: 100%; padding: 6px 8px; }
.filters { display: flex; gap: 8px; align-items: center; padding: 0 12px; }
.pager { display: flex; justify-content: center; padding: 12px; }
</style>